import $config from '@/config/index.config.js';
const upload = async (count = 1) => {
	let baseUrl = $config.baseUrl // baseUrl需要引入，可以在封装的请求方法中获取
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count,
			sizeType: ['original', 'compressed'],
			sourceType: ['album', 'camera'],
			success: res => {
				uni.uploadFile({
					url: baseUrl +
					'/index.php/system/Basic/postUploadOne', //仅为示例，非真实的接口地址
					filePath: res.tempFilePaths[0],
					name: 'img',
					header: {
						Authorization: uni.getStorageSync('token')
					},
					success: r => {
						let imgData = JSON.parse(r.data)
						imgData.showImg = res.tempFilePaths[0]
						resolve(imgData)
					}
				});
			}
		})
	})
}

const uploadVideo = async (type) => {
	let baseUrl = $config.baseUrl // baseUrl需要引入，可以在封装的请求方法中获取
	return new Promise((resolve, reject) => {
		uni.chooseVideo({
			count: 1,
			sizeType: ['original', 'compressed'],
			sourceType: ['album', 'camera'],
			compressed: false,
			success: res => {
				console.log(res)
				 const uploadTask = uni.uploadFile({
					url: baseUrl +
						'/index.php/system/Basic/postUploadTwo', //仅为示例，非真实的接口地址
					filePath: res.tempFilePath,
					name: 'file',
					header: {
						Authorization: uni.getStorageSync('token')
					},
					formData: {
						video: 'abc'
					},
					success: r => {
						let imgData = JSON.parse(r.data)
						imgData.showImg = res.tempFilePath
						resolve(imgData)
					},
					
				});
				// uploadTask.onProgressUpdate((res) => {
				// 	console.log('上传进度' + res.progress);
				// 	console.log('已经上传的数据长度' + res.totalBytesSent);
				// 	console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
				// });
			}
		})
	})
}
// 调用方式：
// 1、在min.js中引入工具类import tool from '@/tool/tool'
// 2、在min.js中注册：Vue.prototype.$upload = tool.upload
// 3、页面调用：this.$upload().then(res => {
//              res为上传接口返回数据
//            })
//统一提示方便全局修改
const msg = (title, duration = 1500, mask = false, icon = 'none') => {
	if (Boolean(title) === false) {
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}
// 获取地址栏中某个key的值，如果没有key，返回false
const getQueryVariable = (key, url) => {
	var query = url.split('?')[1];
	var vars = query.split("&");
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split("=");
		if (pair[0] == key) {
			return pair[1];
		}
	}
	return (false);
}
// 对象转get拼接参数
const objParseParam = (obj) => {
	let paramsStr = '';
	if (obj instanceof Array) return paramsStr;
	if (!(obj instanceof Object)) return paramsStr;
	for (let key in obj) {
		paramsStr += `${key}=${obj[key]}&`;
	}
	return paramsStr.substring(0, paramsStr.length - 1);
}
// 复制--兼容app-h5
const copy = (val) => {
	// #ifdef APP-PLUS
	uni.setClipboardData({
		data: val,
		success() {
			msg('复制成功！')
		},
		fail() {
			msg('复制失败！')
		}
	})
	// #endif
	// #ifdef H5
	msg(h5Copy(val));
	// #endif
}
// H5复制
const h5Copy = (content) => {
	let textarea = document.createElement('textarea');
	textarea.value = content;
	textarea.readOnly = 'readOnly';
	document.body.appendChild(textarea);
	textarea.select(); // 选择对象
	textarea.setSelectionRange(0, content.length); //核心
	let result = document.execCommand('Copy'); // 执行浏览器复制命令
	textarea.remove();
	const msgs = result ? '复制成功' : '复制失败';
	msg(msgs);
}
// 异步获取设备信息
const getInfoAsync = () => {
	return new Promise((resolve, reject) => {
		plus.device.getInfo({
			success(e) {
				resolve(e);
			},
			fail(e) {
				reject(e.message);
			}
		});
	});
}
const openLocation = (latitude, longitude, name, address) => {
	uni.openLocation({
		latitude: latitude,
		longitude: longitude,
		name: name,
		address: address,
		fail(e) {
			msg('地图调用失败，请重试，或者反馈问题！')
		}
	})
}
// 生成随机数
const random = (min, max) => {
	switch (arguments.length) {
		case 1:
			return parseInt(Math.random() * min + 1, 10);
			break;
		case 2:
			return parseInt(Math.random() * (max - min + 1) + min, 10);
			break;
		default:
			return 0;
			break;
	}
}
// 浏览器地址栏参数转对象
const getRequestParameters = (locationhref) => {
	let href = locationhref || '';
	let theRequest = new Object();
	let str = href.split('?')[1];
	if (str != undefined) {
		let strs = str.split('&');
		for (let i = 0; i < strs.length; i++) {
			theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
		}
	}
	return theRequest;
}
const pay = (data, type) => {
	if (type == 'alipay') {
		uni.requestPayment({
			provider: type,
			orderInfo: data,
			// timeStamp: res.data.
			success: res => {
				msg('支付成功')
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/order/index?state=0'
					})
				}, 1000)
			},
			fail(err) {
				msg('支付失败')
			}
		})
	} else {
		console.log(type, data)
		uni.requestPayment({
			provider: type,
			timeStamp: data.timeStamp,
			nonceStr: data.nonceStr,
			package: data.package,
			signType: data.signType,
			paySign: data.paySign,
			success: res => {
				msg('支付成功')
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/order/index?state=0'
					})
				}, 1000)
			},
			fail(err) {
				console.log(err)
				msg('支付失败')
			}
		})
	}
}
//打电话
const phone = (phoneNumber) => {
	//打电话
	uni.makePhoneCall({
		phoneNumber,
	})
}
// app 更新
const update = (updateHost = '') => {
	if (updateHost == '') {
		uni.showToast({
			title: '更新方法：更新域名为必传参数'
		})
		return;
	}
	// #ifdef APP-PLUS
	let updateUrl = (updateHost.indexOf('com/') >= 0 || updateHost.indexOf('cn/') >= 0) ? updateHost +
		'download/index.php?m=version' : updateHost + '/download/index.php?m=version'
	let deviceType = plus.os.name == 'Android' ? 1 : 2;
	plus.runtime.getProperty(plus.runtime.appid, function(updateInfo) {
		uni.request({
			method: 'POST',
			url: updateUrl,
			header: {
				"Content-Type": "application/x-www-form-urlencoded"
			},
			data: {
				current_version: updateInfo.version,
				client_type: deviceType
			},
			success: (data) => {
				console.log(JSON.stringify(data));
				var showLoading = plus.nativeUI.showWaiting("正在下载");
				if (data.data.code == 200) {
					let dask = plus.nativeUI.confirm("系统检测到更新,是否更新", function(e) {
						if (e.index == 0) {
							var newVersion = data.data.result;
							console.log(JSON.stringify(newVersion))
							if (newVersion.pack_type == 0) {
								console.log(0)
								let dask = plus.downloader.createDownload(newVersion
									.pack_file, {
										filename: "_doc/update/"
									},
									function(d, status) {
										console.log(1)
										if (status == 200) {
											plus.runtime.install(d.filename, {
												force: true
											}, function() {
												plus.nativeUI
													.closeWaiting();
												plus.nativeUI.alert(
													"应用资源更新完成！",
													function() {
														plus.runtime
															.restart();
													});
											}, function(e) {
												plus.nativeUI
													.closeWaiting();
											});
										} else {
											console.log("下载wgt失败！");
										}
										plus.nativeUI.closeWaiting();
									})
								dask.addEventListener("statechanged", function(task) {
									let val = Math.round(task.downloadedSize /
										task.totalSize * 100)
									showLoading.setTitle('努力加载中：' + val + '%' ||
										'加载中')
								});
								dask.start();
							} else {
								console.log(newVersion.pack_file)
								if (deviceType == 1) {
									let dask = plus.downloader.createDownload(newVersion
										.pack_file, {
											filename: "_doc/update/"
										},
										function(d, status) {
											if (status == 200) {
												plus.runtime.install(d.filename, {
													force: true
												}, function() {
													plus.nativeUI
														.closeWaiting();
													plus.nativeUI.alert(
														"应用资源更新完成！",
														function() {
															plus.runtime
																.restart();
														});
												}, function(e) {
													plus.nativeUI
														.closeWaiting();
												});
											} else {
												console.log("下载wgt失败！");
											}
											plus.nativeUI.closeWaiting();
										})
									let current = 0
									dask.addEventListener("statechanged", function(task,
										status) {
										let val = Math.round(task
											.downloadedSize / task
											.totalSize * 100)
										showLoading.setTitle('aapp更新中：' + val +
											'%')
									});
									dask.start();
								} else {
									plus.runtime.openURL(data.data.pack_url);
								}
							}
						}
					})
				}
			}
		})
	});
	// #endif
}
const formatDate = (now) => {
	var h = now.getHours();
	var m = now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes();

	return h + ":" + m;
}
export default {
	msg,
	getQueryVariable,
	objParseParam,
	getInfoAsync,
	random,
	getRequestParameters,
	copy,
	upload,
	openLocation,
	pay,
	update,
	formatDate,
	phone,
	uploadVideo
}
